import { ElMessage } from "element-plus";
import * as Api from '@/api/configCenter/configCenter';
import type { CallBackData } from '@/components/dialog/type.d';
import * as BaseDataUtils from './useBaseData';

type DataInfo = {
  visible: boolean;
  title: string;
  width: number;
  isForm: boolean;
  maskClosable: boolean;
  okText: string;
  modalClass: string;
  footer: boolean;
  hideCancel: boolean;
  modelForm: any;
}
export const saveInterface = async (dataInfo: DataInfo, modalData: CallBackData, flag: string): Promise<boolean> => {
  let returnFlag = false;
  try {
    if (flag === BaseDataUtils.viewMode.CREATE) {
      const params = {
        name: dataInfo.modelForm.name,
        type: dataInfo.modelForm.type,
        parameter: dataInfo.modelForm.parameter,
        data: undefined as unknown as string
      }
      if (dataInfo.modelForm.type !== "text") {
        params.data = JSON.stringify(dataInfo.modelForm.data);
      }
      const res = await Api.addComp(params);
      if (res.code === 200) {
        ElMessage.success("新建成功！");
        returnFlag = true;
        dataInfo.visible = modalData.flag;
      }
    } else if(flag === BaseDataUtils.viewMode.EDIT){
      const params = {
        id: dataInfo.modelForm.id,
        name: dataInfo.modelForm.name,
        type: dataInfo.modelForm.type,
        parameter: typeof dataInfo.modelForm.parameter === "string"? dataInfo.modelForm.parameter : JSON.stringify(dataInfo.modelForm.parameter),
        data: undefined as unknown as string
      }
      if (dataInfo.modelForm.type !== "text") {
        params.data = JSON.stringify(dataInfo.modelForm.data);
      }
      const res = await Api.updateComp(params);
      if (res.code === 200) {
        ElMessage.success("编辑成功！");
        dataInfo.visible = modalData.flag;
        returnFlag = true;
      }
    }else{
      //查看模式
      dataInfo.visible = modalData.flag;
      returnFlag = false;
    }
  } catch (error) {
    console.log(error);
    dataInfo.visible = true;
  }
  return returnFlag;
}